<!-- 搜索页面 -->
<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/">
        <van-search
        v-model="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus='isResultShow=false'
        background="#f19066"
        />
    </form>
    <!-- 搜索栏 -->
    <!-- 搜索结果 -->
    <search-result v-if="isResultShow" :searchText='value'/>
    <!-- 搜索结果 -->
    <!-- 搜索历史 -->
    <search-history v-else-if="!value" :searchHistoryText='searchHistoryText'
                    @delete-search-history='deleteSearchHistory'
                    @search='onSearch'
                    @clear-search-history='searchHistoryText=[]'
    />
    <!-- 搜索历史 -->
    <!-- 搜索建议 -->
    <search-suggest v-else :searchText='value' @search='onSearch'/>
    <!-- 搜索建议 -->
  </div>
</template>
<script>
import searchHistory from './components/searchHistory.vue'
import searchResult from './components/searchResult.vue'
import searchSuggest from './components/searchSuggest.vue'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  components: {
    searchHistory,
    searchResult,
    searchSuggest
  },
  data () {
    return {
      value: '',
      isResultShow: false, // 控制搜索结果的显示
      searchHistoryText: getItem('SEARCH_HISTORY') || []
    }
  },
  watch: {
    searchHistoryText: {
      handler (newvalue) {
        setItem('SEARCH_HISTORY', newvalue)
      },
      deep: true
    }
  },
  methods: {
    onSearch (val) {
      // 更新文本框内容
      this.value = val
      // 更新搜索历史文本列表 要求：后来者居前，不能有重复
      const index = this.searchHistoryText.indexOf(val)
      if (index !== -1) {
        // 有重复的
        this.searchHistoryText.splice(index, 1)
      }
      this.searchHistoryText.unshift(val)
      // console.log(this.searchHistoryText)
      // 显示渲染结果
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    },
    deleteSearchHistory (index) {
      this.searchHistoryText.splice(index, 1)
    }
  }
}
</script>

<style  scoped lang="less">
.search-container {
  /deep/.van-search__action {
      color: rgb(255, 255, 255) !important;
  }
}
</style>
